package tcp

import (
	"context"
	"fmt"
	"log"
	"net"
	"sync/atomic"
	"time"

	"internal-net-bridge-server/internal/tunnel/core"
)

// ========================================
// TCP协议监听器实现
// 实现 core.ProtocolListener 接口
// ========================================

// Listener TCP协议监听器
type Listener struct {
	tunnelID  string
	port      string
	listener  net.Listener
	forwarder core.QUICForwarder
	ctx       context.Context
	cancel    context.CancelFunc
	stats     core.ProtocolStats
	isRunning atomic.Bool
}

// NewListener 创建TCP协议监听器
func NewListener(tunnelID, port string, forwarder core.QUICForwarder) *Listener {
	ctx, cancel := context.WithCancel(context.Background())
	return &Listener{
		tunnelID:  tunnelID,
		port:      port,
		forwarder: forwarder,
		ctx:       ctx,
		cancel:    cancel,
	}
}

// Start 实现 ProtocolListener 接口
func (l *Listener) Start() error {
	if l.isRunning.Load() {
		return fmt.Errorf("监听器已在运行")
	}

	listener, err := net.Listen("tcp", fmt.Sprintf(":%s", l.port))
	if err != nil {
		return fmt.Errorf("TCP监听失败: %w", err)
	}

	l.listener = listener
	l.isRunning.Store(true)

	log.Printf("🔌 TCP公共端口监听启动成功: :%s -> 隧道 %s", l.port, l.tunnelID)

	// 启动监听循环
	go l.acceptLoop()

	return nil
}

// Stop 实现 ProtocolListener 接口
func (l *Listener) Stop() error {
	if !l.isRunning.Load() {
		return nil
	}

	l.cancel()
	if l.listener != nil {
		l.listener.Close()
	}
	l.isRunning.Store(false)

	log.Printf("🛑 TCP监听器已停止: :%s", l.port)
	return nil
}

// GetProtocolType 实现 ProtocolListener 接口
func (l *Listener) GetProtocolType() core.ProtocolType {
	return core.ProtocolTCP
}

// GetPort 实现 ProtocolListener 接口
func (l *Listener) GetPort() string {
	return l.port
}

// HandleConnection 实现 ProtocolListener 接口
func (l *Listener) HandleConnection(clientConn net.Conn) {
	defer clientConn.Close()

	clientAddr := clientConn.RemoteAddr().String()
	atomic.AddInt64(&l.stats.TotalRequests, 1)
	atomic.AddInt64(&l.stats.ActiveRequests, 1)
	defer atomic.AddInt64(&l.stats.ActiveRequests, -1)

	log.Printf("🔌 收到TCP连接: 客户端=%s, 隧道ID=%s", clientAddr, l.tunnelID)

	// 生成请求ID
	requestID := fmt.Sprintf("%s-%019d", l.tunnelID[:16], time.Now().UnixNano())

	// 通过QUIC转发TCP连接
	if err := l.forwarder.ForwardTCPConnection(l.tunnelID, requestID, clientConn); err != nil {
		log.Printf("❌ [TCP转发] 转发失败: %v", err)
		atomic.AddInt64(&l.stats.ErrorCount, 1)
		return
	}

	atomic.AddInt64(&l.stats.SuccessCount, 1)
	log.Printf("✅ [TCP转发] 连接完成: RequestID=%s", requestID[:8]+"...")
}

// acceptLoop 接受连接循环
func (l *Listener) acceptLoop() {
	for {
		select {
		case <-l.ctx.Done():
			return
		default:
		}

		clientConn, err := l.listener.Accept()
		if err != nil {
			select {
			case <-l.ctx.Done():
				return
			default:
				log.Printf("⚠️ 接受TCP连接失败: %v", err)
				continue
			}
		}

		// 优化TCP连接
		if tcpConn, ok := clientConn.(*net.TCPConn); ok {
			tcpConn.SetKeepAlive(true)
			tcpConn.SetKeepAlivePeriod(30 * time.Second)
			tcpConn.SetNoDelay(true)
		}

		// 处理连接
		go l.HandleConnection(clientConn)
	}
}

// GetStats 获取统计信息
func (l *Listener) GetStats() core.ProtocolStats {
	return core.ProtocolStats{
		TotalRequests:  atomic.LoadInt64(&l.stats.TotalRequests),
		ActiveRequests: atomic.LoadInt64(&l.stats.ActiveRequests),
		TotalBytesSent: atomic.LoadInt64(&l.stats.TotalBytesSent),
		TotalBytesRecv: atomic.LoadInt64(&l.stats.TotalBytesRecv),
		SuccessCount:   atomic.LoadInt64(&l.stats.SuccessCount),
		ErrorCount:     atomic.LoadInt64(&l.stats.ErrorCount),
	}
}
